package com.xl.sqlSession;

import com.xl.pojo.Configuration;
import com.xl.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

public class DefaultSession implements SqlSession {

    private Configuration configuration;

    public DefaultSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.query(configuration, mappedStatement, params);
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> list = this.selectList(statementId, params);
        if (list.size()==1){
           return (T) list.get(0);
        }else {
            throw new RuntimeException("selectOne error return more...");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {

        /**
         * 1.使用JDK动态代理来为Dao层接口生成动态代理，并返回
         * 2.代理对象调用接口中任意方法，都会执行invoke方法
         */
        Object proxyInstance = Proxy.newProxyInstance(DefaultSession.class.getClassLoader(), new Class<?>[]{mapperClass}, new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                /**
                 * proxy:当前代理对象的应用
                 * method:当前被调用方法的引用
                 * args:传递的参数
                 *
                 * 底层都还是执行JDBC代码，根据不同情况，来调用selectList或者selectOne
                 * 准备参数 1.statementId:sql语句唯一标识：namespace.id = 接口全限定名.方法
                 * 接口全限定名 com.xl.jdbc.dao.IUserDao
                 * 方法名 selectOne
                 */
                String methodName = method.getName();
                String namespace = method.getDeclaringClass().getName();
                String statementId = namespace + "." + methodName;
                Type genericReturnType = method.getGenericReturnType();
                if (genericReturnType instanceof ParameterizedType) {
                    //如果返回参数类型后面带有泛型认为返回的是集合
                    List<Object> objects = selectList(statementId, args);
                    return objects;
                } else {
                    return selectOne(statementId, args);
                }
            }
        });
        return (T) proxyInstance;
    }
}
